package com.goldplusgold.tradedelay.app.home.live.adapter;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.goldplusgold.imageloader.lib.IShow;
import com.goldplusgold.live.LVDataManager;
import com.goldplusgold.live.bean.LMessageBean;
import com.goldplusgold.live.channel.LiveBootstrap;
import com.goldplusgold.live.channel.ResponseHandler;
import com.goldplusgold.live.result.ResultMessages;
import com.goldplusgold.network.lib.http.netty.ChannelBootstrapManager;
import com.goldplusgold.support.lib.utils.BitmapUtil;
import com.goldplusgold.support.lib.utils.ScreenSizeUtil;
import com.goldplusgold.support.lib.widget.VerticalTimeLine;
import com.goldplusgold.tradedelay.app.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
//TODO 优化代码， Bitmap优化 去掉addOnPreDrawListene采用新的方式 方法 by hur
public class TextLiveAdapter extends RecyclerView.Adapter<TextLiveAdapter.ViewHolder> {

    private Context context;
    List<LMessageBean> datas = new ArrayList<>();
    String roomID;
    int count = 10;
    Bitmap videoBitmap;
    Bitmap bitmap ;
    int mBitmapHight ;
    int mBitmapWidth ;
    private  LiveBootstrap liveBootstrap ;
    private  ResponseHandler.ReceiverMessageInterface receiverMessageInterface ;

    public TextLiveAdapter(Context mContext, String roomID) {
        this.context = mContext;
        this.roomID = roomID;

        if(videoBitmap == null){
            bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.live_pic_default);
            int height = (context.getResources().getDisplayMetrics().widthPixels ) /(bitmap.getWidth() / bitmap.getHeight());
            videoBitmap = BitmapUtil.scale(bitmap,context.getResources().getDisplayMetrics().widthPixels,height);
            mBitmapHight = videoBitmap.getHeight() ;
            mBitmapWidth = videoBitmap.getWidth() ;

        }
        receiverMessageInterface = new ResponseHandler.ReceiverMessageInterface() {
            @Override
            public void onReceiver(final LMessageBean bean) {
                insertData(bean);
            }

            @Override
            public void onTakeBack(String id) {
                takeBack(id);
            }
        };
        liveBootstrap = new LiveBootstrap(roomID, receiverMessageInterface);
        ChannelBootstrapManager.getInstance().register(LiveBootstrap.class.getName(), liveBootstrap );
        requestData();
    }

    private void takeBack(String id) {
        for(LMessageBean bean:datas){
            if(bean.getId().equals(id)){
                datas.remove(bean);
                break;
            }
        }
        notifyChange();
    }

    private void insertData(LMessageBean bean) {
        datas.add(0, bean);
        notifyChange();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.live_detail_listview_item, parent, false);
        return new ViewHolder(convertView);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        bindData(holder, position);
    }

    @Override
    public int getItemCount() {
        if (datas != null) {
            return datas.size();
        }
        return 0;
    }

    public void pullUp(){
        if(datas.size() >= count){
            count = count +10;
            requestData();
        }
    }

    private void requestData() {
        LVDataManager.getInstance().getHistoryMessages(roomID, "", count, new Callback<ResultMessages>() {
            @Override
            public void onResponse(Call<ResultMessages> call, Response<ResultMessages> response) {
                setDatas(response.body().getMessages());
            }

            @Override
            public void onFailure(Call<ResultMessages> call, Throwable t) {

            }
        });
    }

    public void setDatas(List<LMessageBean> datas) {
        if(datas != null && datas.size() > 0){
            this.datas = datas;
        }
        notifyChange();
    }

    private void notifyChange() {
        notifyDataSetChanged();
    }

    private void bindData(final ViewHolder holder, final int position) {
        long lt = new Long(datas.get(position).getTime());
        Date date = new Date(lt);
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        final String dateString = formatter.format(date);
        holder.info.setText(datas.get(position).getContent());
        holder.time.setPosition(position);
        holder.time.setTime(dateString);
        int type = datas.get(position).getMediaType();
        final String imageUri = datas.get(position).getMediaUri();
        holder.itemView.setTag(position);
        if(type > 12 && type < 34){
            holder.img.setVisibility(View.VISIBLE);

            holder.img.setImageBitmap(videoBitmap);
            /*IShow.getInstance().show(context , R.drawable.live_pic_default,
                    holder.img , ScreenSizeUtil.dip2px(context  , 155) ,
                    ScreenSizeUtil.dip2px(context , 75));*/

            ViewTreeObserver viewTreeObserver = holder.info.getViewTreeObserver();
            viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    LinearLayout.LayoutParams param = (LinearLayout.LayoutParams) holder.info.getLayoutParams();
                    final int timeHeight = mBitmapHight + holder.info.getHeight() + param.bottomMargin+param.topMargin;
                    holder.time.setSize(Math.max(holder.mView.getMeasuredHeight(),timeHeight));
                    holder.info.getViewTreeObserver().removeOnPreDrawListener(this);
                    return true;
                }
            });
            holder.img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int pos = (int) holder.itemView.getTag();
                    int type = datas.get(pos).getMediaType();
                    if(type > 12 && type < 34) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.parse(datas.get(position).getMediaUri()), "video/mp4");
                        context.startActivity(intent);
                    }
                }
            });
        } else if(type > 0 && type < 12 && !TextUtils.isEmpty(imageUri) ){
            int start = imageUri.lastIndexOf("/");
            int end = imageUri.length();
            String fileName = imageUri.substring(start + 1, end);
            int begin = fileName.lastIndexOf("_");
            int finish = fileName.lastIndexOf(".");
            String widthHeight = fileName.substring(begin + 1, finish);
            String[] imageInfos = widthHeight.split("x");
            if (imageInfos.length != 2) {
                return;
            }
            final int imageWidth = Integer.parseInt(imageInfos[0]);
            final int imageHeight = Integer.parseInt(imageInfos[1]);
            holder.img.setVisibility(View.VISIBLE);
            final int width = ScreenSizeUtil.dip2px(context, imageWidth);
            final int height = ScreenSizeUtil.dip2px(context, imageHeight);
            Bitmap bt = BitmapUtil.scale(Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565),width,height);
            holder.img.setImageBitmap(bt);
            final LinearLayout.LayoutParams param = (LinearLayout.LayoutParams) holder.info.getLayoutParams();
            final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) holder.img.getLayoutParams();
            int timeHeight = bt.getHeight() + params.bottomMargin+ params.topMargin + holder.info.getMeasuredHeight() + param.bottomMargin+param.topMargin;
            holder.time.setSize(Math.max(holder.mView.getMeasuredHeight(),timeHeight));
            Glide.with(context)
                    .load(datas.get(position).getMediaUri())
                    .asBitmap()
                    .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                        @Override
                        public void onResourceReady(final Bitmap bitmap, GlideAnimation glideAnimation) {
                            if(holder.img.getVisibility() == View.VISIBLE){
                                final Bitmap cacheBitmap = Bitmap.createBitmap(bitmap);
                                final LinearLayout.LayoutParams param = (LinearLayout.LayoutParams) holder.info.getLayoutParams();
                                final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) holder.img.getLayoutParams();
                                final int width = ScreenSizeUtil.dip2px(context, cacheBitmap.getWidth());
                                final int height = ScreenSizeUtil.dip2px(context, cacheBitmap.getHeight());
                                final Bitmap cache = BitmapUtil.scale(cacheBitmap,width,height);
                                holder.img.setImageBitmap(cache);
                                ViewTreeObserver viewTreeObserver = holder.info.getViewTreeObserver();
                                viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                                    @Override
                                    public boolean onPreDraw() {
                                        int timeHeight = height + params.bottomMargin+ params.topMargin + holder.info.getHeight() + param.bottomMargin+param.topMargin;
                                        holder.time.setSize(Math.max(holder.mView.getMeasuredHeight(),timeHeight));
                                        holder.info.getViewTreeObserver().removeOnPreDrawListener(this);
                                        return true;
                                    }
                                });
                            }
                        }
                    });
        } else{
            holder.img.setVisibility(View.GONE);
            final LinearLayout.LayoutParams param = (LinearLayout.LayoutParams) holder.info.getLayoutParams();
            ViewTreeObserver viewTreeObserver = holder.info.getViewTreeObserver();
            viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    int timeHeight = holder.info.getHeight() +param.topMargin + param.bottomMargin;
                    holder.time.setSize(timeHeight);
                    holder.info.getViewTreeObserver().removeOnPreDrawListener(this);
                    return true;
                }
            });

        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView info;
        public VerticalTimeLine time;
        public ImageView img;
        public final View mView;

        public ViewHolder(View view) {
            super(view);
            this.mView = view;
            info = (TextView) mView.findViewById(R.id.live_detail_listview_info);
            time = (VerticalTimeLine) mView.findViewById(R.id.live_detail_listview_time);
            img = (ImageView) mView.findViewById(R.id.live_detail_listview_img);
        }
    }


    public void onChannleCancel(){
        receiverMessageInterface = null ;
        ChannelBootstrapManager.getInstance().unregister(LiveBootstrap.class.getName());
        liveBootstrap = null ;
        if(!videoBitmap.isRecycled()){
            videoBitmap.recycle();
            videoBitmap = null ;
        }
        if(!bitmap.isRecycled()){
            bitmap.recycle();
            bitmap = null ;
        }
    }
}
